﻿namespace DoNet.WechatPay
{
    /// <summary>
    /// 请求参数基类
    /// </summary>
    public class ParameterBase
    {
        /// <summary>
        /// 请求参数列表
        /// 采用排序的Dictionary的好处是方便对数据包进行签名，不用再签名之前再做一次排序
        /// </summary>
        protected SortedDictionary<string, object> Parameters;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ParameterBase()
        {
            Parameters = new SortedDictionary<string, object>();
        }

        /// <summary>
        /// 设置某个字段的值
        /// </summary>
        /// <param name="key">字段名</param>
        /// <param name="value">字段值</param>
        public void SetValue(string key, object value)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                if (Parameters.ContainsKey(key))
                {
                    Parameters.Remove(key);
                }
                Parameters.Add(key, value);
            }
        }

        /// <summary>
        /// 根据字段名获取某个字段的值
        /// </summary>
        /// <param name="key">字段名</param>
        /// <returns></returns>
        public object? GetValue(string key)
        {
            Parameters.TryGetValue(key, out object? value);
            return value;
        }

        /// <summary>
        /// 判断某个字段是否已设置
        /// </summary>
        /// <param name="key">字段名</param>
        /// <returns>若字段key已被设置，则返回true，否则返回false</returns>
        public bool IsSet(string key)
        {
            Parameters.TryGetValue(key, out object? value);
            if (value != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 获取所有参数 Hashtable
        /// </summary>
        /// <returns></returns>
        public SortedDictionary<string, object> GetAllParameters()
        {
            return Parameters;
        }
    }
}
